import Vue from 'vue';
import Axios from 'axios';
import ApiUrl from '@/constant/ApiUrl';
import CommonUnit from '@/unit/CommonUnit';
import {Route} from 'vue-router';
import store from '@/store/index';
import Http from '@/service/Http';
import {exitUser, updateUser} from '@/store/dispatches';
import {InterfaceUser} from '@/interface/InterfaceUser';
import DeviceStore from '@/store/modules/DeviceStore';
// import

export default class Scene extends Vue {
    public api = ApiUrl;
    public imageFileDoamin = 'http://wx.chuangyijiaoyu2018.com/';
    public domain = 'https://www.xxyhl.cn/';
    public webPath = this.domain + 'love.html';
    public cryptoKey: string = 'sgg45747ss223411';
    public onShareMessage: any = {
        title: '分享',
        desc: '11',
        thumb: `${this.webPath}`,
    };


    public constructor() {
        super();

        if (process.env.NODE_ENV === 'development') {
            ApiUrl.url = '/site/';
        } else if (window.location.protocol === 'file:' || window.location.protocol === 'files:') {
            ApiUrl.url = 'http://www.xxyhl.cn/';
        }

        // if (window.history && window.history.pushState) {
        //     window.addEventListener('popstate', (e) => {
        //         window.history.pushState('', '', '');
        //     });
        // }
    }

    public get shareUrl(): string {
        const storeState: any = store.state;
        return `${window.location.origin}${(this as any).$router.options.base || ''}?${storeState.UserStore.token !== '' ? 'share=' + storeState.UserStore.userId : ''}&url=${encodeURIComponent(this.$route.fullPath)}`;
    }

    public navigateTo(obj: any, auth: boolean = true): void {
        const storeState: any = store.state;
        if (storeState.DeviceStore.status && storeState.SettingStore.SoundAndShock.actionShock) {
            navigator.vibrate(200);
        }
        obj.query = {...obj.query, referer: this.$route.name};
        this.$router.push(obj);
        if (auth) {
            this.authentication();
        }
    }

    public switchTab(obj: any) {
        const storeState: any = store.state;
        if (storeState.DeviceStore.status && storeState.SettingStore.SoundAndShock.actionShock) {
            navigator.vibrate(200);
        }
        this.$router.replace(obj);
        this.authentication();
    }

    public navigateBack(n: number = -1, auth: boolean = true): void {
        const storeState: any = store.state;
        if (storeState.DeviceStore.status && storeState.SettingStore.SoundAndShock.actionShock) {
            navigator.vibrate(200);
        }
        if (this.$route.query.referer && window.history.length > 1) {
            this.$router.go(n);
        } else {
            this.reLaunch();
        }
        if (auth) {
            this.authentication();
        }
    }

    public reLaunch(): void {
        this.$router.replace({path: '/'});
    }

    public redirectTo(obj: any = {}, auth: boolean = true): void {
        if (!obj.name && !obj.path) {
            this.$router.replace({path: '/'});
        } else {
            if (this.$route.query.referer) {
                obj.query = {...obj.query, referer: this.$route.name};
            }

            this.$router.replace(obj);
        }
        if (auth) {
            this.authentication();
        }
    }

    public navigateLoginPage(): void {
        this.redirectTo({name: 'loginRegister'}, false);
    }

    public imageUrlHandle(str: string): string {
        return this.imageFileDoamin + String(str);
    }

    public globalSingleResultToast(res: any): boolean {
        (this as any).$createToast({
            mask: true,
            type: 'error',
            time: 2500,
            zIndex: 1000,
            txt: res.msg,
            onTimeout: () => {
                if (!CommonUnit.responseLoginVerification(res)) {
                    exitUser();
                    this.navigateLoginPage();
                }
            },
        }).show();
        return CommonUnit.responseLoginVerification(res);
    }

    public globalMultipleResultToast(...arg: any): boolean {
        const errorList: string[] = [];
        let loginResult: boolean = true;
        for (const error of arg) {
            if (error.code !== 1) {
                errorList.push(error.msg);
            }
            if (error.code === -1) {
                loginResult = false;
            }
        }
        const virtual: any = {
            msg: errorList.join(','),
            code: loginResult ? 0 : -1,
            data: '',
        };

        (this as any).$createToast({
            mask: true,
            type: 'error',
            time: 2500,
            zIndex: 1000,
            txt: virtual.msg,
            onTimeout: () => {
                if (!CommonUnit.responseLoginVerification(virtual)) {
                    this.navigateLoginPage();
                }
            },
        }).show();
        return CommonUnit.responseLoginVerification(virtual);
    }

    public authentication(): void {
        const storeState: any = store.state;
        if (this.$route.meta.loginAuth) {
            Http.get(this.api.getUserInfo, {}, {token: storeState.UserStore.token}).then((res) => {
                if (res.code === 1) {
                    const user: any = {...res.data, ...res.data.user_info};
                    delete user.user_info;
                    const userData = CommonUnit.objectUnderlineToHump(user);
                    updateUser(userData);
                    if (userData.must.code < 1 && userData.user_rank < 4) {
                        (this as any).$createToast({
                            mask: true,
                            type: 'error',
                            time: 2500,
                            zIndex: 1000,
                            txt: userData.must.msg,
                            onTimeout: () => {
                                this.redirectTo({
                                    name: 'mineDataEdit',
                                    query: {type: 'baseData'},
                                }, false);
                            },
                        }).show();
                    }
                    if (CommonUnit.wechatBrowser()) {
                        const shareTitle = `我是${user.nickname},我在心相依婚恋，快来找我吧。`;
                        const shareDesc = user.introduction;
                        const shareLink = `https://www.xxyhl.cn/love.html#/loginRegister?shareCode=${user.code}`;
                        const shareImgUrl = user.avatarId > 0 ? user.avatar.filePath : 'https://www.xxyhl.cn/img/icons/logo.png';

                        try {
                            (window as any).updateAppMessageShareData({
                                title: shareTitle, // 分享标题
                                desc: shareDesc, // 分享描述
                                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: shareImgUrl, // 分享图标
                                success: () => {
                                    (this as any).$createToast({
                                        type: 'correct',
                                        time: 2500,
                                        zIndex: 1000,
                                        txt: '分享成功',
                                    }).show();
                                },
                            });
                            (window as any).wx.updateTimelineShareData({
                                title: shareTitle, // 分享标题
                                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: shareImgUrl, // 分享图标
                                success: () => {
                                    (this as any).$createToast({
                                        type: 'correct',
                                        time: 2500,
                                        zIndex: 1000,
                                        txt: '分享成功',
                                    }).show();
                                },
                            });
                        } catch (e) {
                            // tslint:disable-next-line:no-console
                            console.log(e);
                        }
                    }
                } else {
                    this.globalSingleResultToast(res);
                }
            });
        }
    }

    public userFaceSafeHandle(user: any): any {
        const defaultFace: any = {
            extension: 'jpg',
            file_name: 'user-no-face.jpg',
            file_path: user.gender === 2 ? require('@/assets/images/default-user-face-women.png') : require('@/assets/images/default-user-face-mam.png'),
            file_size: 6103,
            file_status: {id: 0, user_id: user.userId, file_id: 0, content: '', type: 1, status: 1},
            file_type: 'image',
            file_url: 'localhost',
            group_id: 2,
            id: 0,
            is_delete: 0,
            is_user: 1,
            storage: 'localhost',
        };
        if (user.avatar_id === 0) {
            return defaultFace;
        } else if (user.avatar.file_status.status !== 1) {
            return defaultFace;
        } else {
            return user.avatar;

        }
    }

    public getWeChatCode(url: string): void {
        if (CommonUnit.wechatBrowser()) {
            window.location.href = 'https://www.xxyhl.cn/api/v1/getCode?url=' + url;
        }
    }
}


